package org.springframework.android.showcase.location;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.iside.android.showcase.R;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapView;
import com.baidu.mapapi.MyLocationOverlay;

public class CustomerLocationNearBy extends MapActivity {

    CAsyncListActivity cAsyncListActivity = new CAsyncListActivity();
	MapView mMapView = null;
	LocationListener mLocationListener = null;//onResume时注册此listener，onPause时需要Remove
	MyLocationOverlay mLocationOverlay = null;	//定位图层
	
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
        setContentView(R.layout.mapviewdemo);
        
		BMapApiDemoApp app = (BMapApiDemoApp)this.getApplication();
		if (app.mBMapMan == null) {
			app.mBMapMan = new BMapManager(getApplication());
			app.mBMapMan.init(app.mStrKey, new BMapApiDemoApp.MyGeneralListener());
		}
		app.mBMapMan.start();
        // 如果使用地图SDK，请初始化地图Activity
        super.initMapActivity(app.mBMapMan);
        
        mMapView = (MapView)findViewById(R.id.bmapView);
        mMapView.setBuiltInZoomControls(true);
        //设置在缩放动画过程中也显示overlay,默认为不绘制
        mMapView.setDrawOverlayWhenZooming(true);
        
		// 添加定位图层
        mLocationOverlay = new MyLocationOverlay(this, mMapView);
        mLocationOverlay.enableMyLocation(); // 启用定位
        mLocationOverlay.enableCompass();    // 启用指南针
		mMapView.getOverlays().add(mLocationOverlay);
		
//		mMapView.getOverlays().add(new MyOverlay());
		
//		Drawable marker = getResources().getDrawable(R.drawable.iconmarka);  //得到需要标在地图上的资源
//		mMapView.getOverlays().add(new OverItemLay(marker, this)); //添加ItemizedOverlay实例到mMapView
		
        // 注册定位事件
        mLocationListener = new LocationListener(){

			@Override
			public void onLocationChanged(Location location) {
				if (location != null){
					GeoPoint pt = new GeoPoint((int)(location.getLatitude()*1e6),
							(int)(location.getLongitude()*1e6));
					mMapView.getController().animateTo(pt);
				}
			}
        };
	}

	@Override
    public void onStart() {
        super.onStart();

        // when this activity starts, initiate an asynchronous HTTP GET request
        new DownloadStatesTask().execute();
    }
	
	@Override
	protected void onPause() {
		BMapApiDemoApp app = (BMapApiDemoApp)this.getApplication();
		app.mBMapMan.getLocationManager().removeUpdates(mLocationListener);
		mLocationOverlay.disableMyLocation();
        mLocationOverlay.disableCompass(); // 关闭指南针
		app.mBMapMan.stop();
		super.onPause();
	}
	@Override
	protected void onResume() {
		BMapApiDemoApp app = (BMapApiDemoApp)this.getApplication();
		// 注册定位事件，定位后将地图移动到定位点
        app.mBMapMan.getLocationManager().requestLocationUpdates(mLocationListener);
        mLocationOverlay.enableMyLocation();
        mLocationOverlay.enableCompass(); // 打开指南针
		app.mBMapMan.start();
		super.onResume();
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	private class DownloadStatesTask extends AsyncTask<Void, Void, List<org.springframework.android.showcase.location.Location>> {

        @Override
        protected void onPreExecute() {
            // before the network request begins, show a progress indicator
//            cAsyncListActivity.showLoadingProgressDialog();
        }

        @Override
        protected List<org.springframework.android.showcase.location.Location> doInBackground(Void... params) {
            try {
                // The URL for making the GET request
                final String url = getString(R.string.base_uri) + "/listtaxilocations";

                // Set the Accept header for "application/json"
                HttpHeaders requestHeaders = new HttpHeaders();
                List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
                acceptableMediaTypes.add(MediaType.APPLICATION_JSON);
                requestHeaders.setAccept(acceptableMediaTypes);

                // Populate the headers in an HttpEntity object to use for the
                // request
                HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders);

                // Create a new RestTemplate instance
                RestTemplate restTemplate = new RestTemplate();

                // Perform the HTTP GET request
                ResponseEntity<org.springframework.android.showcase.location.Location[]> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, org.springframework.android.showcase.location.Location[].class);
                
                // convert the array to a list and return it
                return Arrays.asList(responseEntity.getBody());
            } catch (Exception e) {
                Log.e(CAsyncListActivity.TAG, e.getMessage(), e);
            }

            return null;
        }

        @Override
        protected void onPostExecute(List<org.springframework.android.showcase.location.Location> result) {
            // hide the progress indicator when the network request is complete
            cAsyncListActivity.dismissProgressDialog();

            // return the list of states
            showResult(result);
        }

    }
	
	private void showResult(List<org.springframework.android.showcase.location.Location> result) {
	    Drawable marker = getResources().getDrawable(R.drawable.taxiposition);  //得到需要标在地图上的资源
        mMapView.getOverlays().add(new OverItemLay(marker, this, result)); //添加ItemizedOverlay实例到mMapView
    }
}
